import React, {Component} from 'react';
import './App.css';
import {createShader,createProgram} from './util/util';
import vs from './glsl/simpleVertexShader'
import fs from './glsl/simpleFragShader';

class App extends Component {
    componentDidMount() {
        const gl = this.webglCanvas.getContext("webgl");
        if (!gl){
            console.log("can't get webgl context");
        }
        const vss = createShader(gl, gl.VERTEX_SHADER,vs);
        const fss = createShader(gl, gl.FRAGMENT_SHADER,fs);
        const program = createProgram(gl,vss,fss);
        const positionAttributeLocation = gl.getAttribLocation(program,"a_position");
        const positionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);
        const resolutionUniformLocation = gl.getUniformLocation(program, "u_resolution");
        const positions =[
            10, 20,
            80, 20,
            10, 30,
            10, 30,
            80, 20,
            80, 30,
        ];
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(positions),gl.STATIC_DRAW);
        gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
        // Clear the canvas
        gl.clearColor(0, 0, 0, 0);
        gl.clear(gl.COLOR_BUFFER_BIT);
        // Tell it to use our program (pair of shaders)
        gl.useProgram(program);
        // set the resolution
        gl.uniform2f(resolutionUniformLocation, gl.canvas.width, gl.canvas.height);
        gl.enableVertexAttribArray(positionAttributeLocation);
        // Bind the position buffer.
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

        // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
        const size = 2;          // 2 components per iteration
        const type = gl.FLOAT;   // the data is 32bit floats
        const normalize = false; // don't normalize the data
        const stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
        const offset = 0;        // start at the beginning of the buffer
        gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
        const primitiveType = gl.TRIANGLES;
        //const offset = 0;
        const count = 6;
        gl.drawArrays(primitiveType, offset, count);
    }

    render() {
        return (
            <canvas
                style={{width:'100%',height:'100%'}}
                ref={element=>this.webglCanvas=element}>
            </canvas>
        );
    }
}

export default App;
